package com.ys.chatserver.http.logic.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ys.chatserver.http.logic.LogicProcessor2;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.util.Base64;
import java.util.Calendar;
import java.util.Date;
import java.util.Vector;

public class JwtHelper {

    public static final String JWT_ID = "jwt";

    private static final String profiles = "ys";

    private static final String JWT_SECRET = "yAdT2IZPbwAe74uJSSzcBVCtnAf2UqFU";

    /**
     * token过期时间
     */
    private static final Integer EXPORT_TIME = 180;

    /**
     * 由字符串生成加密key
     */
    public static SecretKey generalKey() {
        String stringKey = profiles + JWT_SECRET;
        byte[] encodedKey = Base64.getDecoder().decode(stringKey);
        return new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
    }

    /**
     * 创建jwt
     */
    public String createJWT(String id, String subject, long ttlMillis) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        SecretKey key = generalKey();
        JwtBuilder builder = Jwts.builder()
                .setId(id)
                .setIssuedAt(now)
                .setSubject(subject)
                .signWith(signatureAlgorithm, key);
        if (ttlMillis >= 0) {
            long expMillis = nowMillis + ttlMillis;
            Date exp = new Date(expMillis);
            builder.setExpiration(exp);
        }
        return builder.compact();
    }

    public static String createJWT(String id, String subject, boolean isDevice) throws Exception {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, EXPORT_TIME);
        SecretKey key = generalKey();
        JwtBuilder builder = Jwts.builder()
                .setId(id)
                .setIssuedAt(now)
                .setSubject(subject)
                .signWith(signatureAlgorithm, key);
        if (!isDevice) {//如果是设备登录,不设置过期时间限制
            builder.setExpiration(calendar.getTime());
        }
        return builder.compact();
    }

    /**
     * 解密jwt
     */
    public static Claims parseClams(String jwt) {
        SecretKey key = generalKey();
        return Jwts.parser()
                .setSigningKey(key)
                .parseClaimsJws(jwt).getBody();
    }


    /**
     * 生成subject信息
     */
    public static String generalSubject(JwtParam jwtParam) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.writeValueAsString(jwtParam);
    }


    /**
     * 通过token 获取用户Id
     */
    public static JwtParam parseJwt(String token) throws IOException {
        Claims claims = parseClams(token);
        String subject = claims.getSubject();
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.readValue(subject, JwtParam.class);
    }

    /**
     * token 校验
     */
    public static boolean tokenAuth(JwtParam jwtParam) throws Exception {
        String sql = "select latest_login_time2 from g_users where del_flag = 0 and user_uid = '" + jwtParam.getUserId() + "'";
        Vector<Vector<?>> vectors = LogicProcessor2.db.queryData(sql);
        return !vectors.isEmpty();
    }
}
